//
//  ChatViewModel.swift
//  IMUIDemo
//
//  Created by tbbMacmini on 2025/3/22.
//

import UIKit
import RxSwift
import RxRelay
import RxCocoa

class ChatViewModel {
    
    let messagesRelay = BehaviorRelay<[ChatMessagesModel]>(value: [])
    
    private var totalTime = 3600;
    
    let disposeBag: DisposeBag = DisposeBag()
    
    
    lazy var timerManager: TimerManager = {
        let timerManager = TimerManager();
        return timerManager;
    }()
    
    func sendText(text:String){
        let msg = ChatMessagesModel(mySelf: true, type: .text, text: text)
        send(message: msg)
    }
    
    func sendImage(image:UIImage){
        let msg = ChatMessagesModel(mySelf: true, type: .image, image:image)
        send(message: msg)
    }
    
    private func send(message:ChatMessagesModel){
        var currentMessages = messagesRelay.value;
        currentMessages.append(message)
        
        receive()
        
        messagesRelay.accept(currentMessages)
        
        if(totalTime > 0) {
            withTime()
        }
    }
    
    private func withTime() {
        timerManager.startTimer();
        timerManager.timeTaskBlock = { [weak self] in
            if let self = self {
                totalTime = totalTime - 5;
                if(0 >=  totalTime){
                    timerManager.stopTimer()
                }
                print("---\(self.totalTime)");
                DispatchQueue.main.async {
                    self.showTime(second: self.totalTime)
                }
            }
            
        }
    }
    
    private func showTime(second:Int) {
        var currentMessages = messagesRelay.value;
        var last = currentMessages.last;
        let str = "还有多少秒：\(second)"
        let msg = ChatMessagesModel(mySelf: true, type: .time, text: str)
        if(last?.type == .time){
            currentMessages.removeLast();
        }
        
        currentMessages.append(msg)
        
        messagesRelay.accept(currentMessages)
    }
    
    private func receive(){
        let delayTime: DispatchTimeInterval = .milliseconds(500)
        DispatchQueue.main.asyncAfter(deadline: .now() + delayTime) {
            var currentMessages = self.messagesRelay.value;
            let msg = ChatMessagesModel(mySelf: false, type: .text, text: "收到")
            currentMessages.append(msg)
            self.messagesRelay.accept(currentMessages)
        }
    }
    

    func withBind(chatTableView:UITableView) {
        messagesRelay
            .bind(to: chatTableView.rx.items) { tableView, row, message in
                if(!message.mySelf){
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ChatTableViewOtherTextCell") as? ChatTableViewOtherTextCell else {
                        return UITableViewCell()
                    }
                    cell.contentLable.text = message.text;
                    return cell;
                }
                
                if(message.type == .text){
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ChatTableViewSelfTextCell") as? ChatTableViewSelfTextCell else {
                        return UITableViewCell()
                    }
                    cell.contentLable.text = message.text;
                    return cell;
                }else if(message.type == .image){
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ChatTableViewSelfImageViewCell") as? ChatTableViewSelfImageViewCell else {
                        return UITableViewCell()
                    }
                    cell.chatImageView.image = message.image;
                    
                    return cell;
                }else{
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ChatTableViewTimeCell") as? ChatTableViewTimeCell else {
                        return UITableViewCell()
                    }
                    cell.contentLable.text = message.text;
                    return cell;
                }
            }.disposed(by: disposeBag)
    }


}


class TimerManager {
    var dispatchTimer: DispatchSourceTimer?

    var timeTaskBlock:(()->())?
    // 启动定时器
    func startTimer() {
        // 创建一个 DispatchSourceTimer
        let queue = DispatchQueue.global(qos: .background)
        dispatchTimer = DispatchSource.makeTimerSource(queue: queue)
        
        // 设置定时器的时间间隔（5 秒）和重复模式
        dispatchTimer?.schedule(deadline: .now()+5, repeating: 5.0)
        
        // 设置定时器的触发事件
        dispatchTimer?.setEventHandler { [weak self] in
            self?.timerFired()
        }
        
        // 启动定时器
        dispatchTimer?.resume()
    }

        // 定时器触发时的回调方法
        private func timerFired() {
            timeTaskBlock?()
        }

        // 停止定时器
        func stopTimer() {
            dispatchTimer?.cancel()
            dispatchTimer = nil
            print("定时器已停止")
        }
    }

